#include "../common.h"
#include <stdarg.h>

const char * str_maker(const char * fmt,...){
    size_t size=32,n=strlen(fmt)+1;
    while(size<=n) size<<=1;
    va_list ap;
    char * buff=malloc(size);
    va_start(ap,fmt);
    int len=vsnprintf(buff,size,fmt,ap);
    while(len<=0||len>=size){
        free(buff);
        size<<=1;
        buff=malloc(size);
        va_start(ap,fmt);
        len=vsnprintf(buff,size,fmt,ap);
    }
    #ifdef DEBUG
    //puts(buff);
    #endif
    return buff;
}

const char * deep_copy(const char * s){
    return str_maker("%s",s);
}

List list_insert(List self, void * pointer){
    NEW_V(now,struct list_,.pointer=pointer,.nxt=NULL,.prev=self.end)
    if(self.end) self.end->nxt=now;
    else self.begin=now;
    self.end=now;
    return self;
}

List list_delete(List self,list now){
    if(now->nxt) now->nxt->prev=now->prev;
    else self.end=now->prev;
    if(now->prev) now->prev->nxt=now->nxt;
    else self.begin=now->nxt;
    DELETE(now);
    return self;
}

void list_clear(List self){
    list nxt2=NULL;
    FOR_LIST_2(iter,self,nxt2){
        nxt2=iter->nxt;
        LIST_DELETE(self,iter);
    }
}
